let correctHour;
let attempts = 0;
const maxAttempts = 3;

// 页面加载完成后立即渲染时钟刻度
document.addEventListener('DOMContentLoaded', renderClockMarkings);
document.getElementById('start-button').addEventListener('click', startGame);

function renderClockMarkings() {
  const clock = document.getElementById('clock');
  // 保留指针元素
  const hands = `
        <div class="hour-hand"></div>
        <div class="minute-hand"></div>
    `;
  clock.innerHTML = hands;

  const radius = 90; // 时钟半径
  const centerOffset = 100; // 时钟中心点偏移量
  for (let i = 1; i <= 12; i++) {
    const angle = (i * 30 - 90) * (Math.PI / 180); // 转换为弧度
    const marking = document.createElement('div');
    marking.className = 'marking';

    // 使用三角函数计算位置
    const x = centerOffset + radius * Math.cos(angle);
    const y = centerOffset + radius * Math.sin(angle);

    marking.style.left = `${x}px`;
    marking.style.top = `${y - 14}px`; // 减去刻度高度的一半(15/2)以居中
    marking.style.transform = `rotate(${i * 30}deg)`;

    // 为主要刻度添加数字
    if (i === 3 || i === 6 || i === 9 || i === 12) {
      const number = document.createElement('span');
      number.textContent = i;
      number.className = 'clock-number';
      number.style.transform = `rotate(-${i * 30}deg)`; // 保持数字正向
      marking.appendChild(number);
    }

    clock.appendChild(marking);
  }
}

function startGame() {
  correctHour = Math.floor(Math.random() * 12) + 1;
  attempts = 0;
  document.querySelector('.hour-hand').style.display = 'none';
  document.querySelector('.minute-hand').style.display = 'none';
  document.getElementById('message').innerHTML = '请猜一个小时（1-12）：<input type="number" id="guess-input" min="1" max="12"><button onclick="makeGuess()">猜</button>';
}

function makeGuess() {
  const guess = parseInt(document.getElementById('guess-input').value);
  attempts++;
  if (guess === correctHour) {
    showResult(true);
  } else if (attempts >= maxAttempts) {
    showResult(false);
  } else {
    const hint = guess > correctHour ? '大了' : '小了';
    document.getElementById('message').innerHTML += `<p>猜错了！${hint}。你还有 ${maxAttempts - attempts} 次机会。</p>`;
  }
}

function showResult(isCorrect) {
  const message = isCorrect ? '答对了！' : `答错了！正确答案是 ${correctHour} 点。`;
  document.getElementById('message').innerHTML = `<p>${message}</p>`;
  document.querySelector('.hour-hand').style.display = 'block';
  document.querySelector('.minute-hand').style.display = 'block';
  if (isCorrect) {
    document.querySelector('.hour-hand').style.animation = 'correct-animation 1s infinite';
  }
}
